//初始化审批对象
var audit ={};

//初始化表格
var initGrid = function(){
	$('#approveTable').dataTable({
		"bProcessing" : true, //DataTables载入数据时，是否显示‘进度’提示
        "bServerSide" : true, //是否启动服务器端数据导入
        "bStateSave" : false, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
        "bJQueryUI" : true, //是否使用 jQury的UI theme
        "aLengthMenu" : [5, 10, 15], //更改显示记录数选项
        "iDisplayLength" : 10, //默认显示的记录数
        "bAutoWidth" : true, //是否自适应宽度 update\
        "bScrollCollapse" : false, //是否开启DataTables的高度自适应，当数据条数不够分页数据条数的时候，插件高度是否随数据条数而改变
        "bPaginate" : true, //是否显示（应用）分页器
        "bInfo" : true, //是否显示页脚信息，DataTables插件左下角显示记录数
        "sPaginationType" : "full_numbers", //详细分页组，可以支持直接跳转到某页
        "bSort" : true, //是否启动各个字段的排序功能
        "aaSorting" : [[9, "ASC"]], //默认的排序方式，第9列，升序排列
        "bFilter" : false, //是否启动过滤、搜索功能
        "sScrollX": "100%",
		"sScrollXInner": 1695,
        "sPaginationType": "full_numbers",
	    "sAjaxSource":"sys/Loan/list",
        "fnServerData":retrieveData,  //自定义数据获取函数
		"aoColumns" : [ {
			"mDataProp" : "id",
			"sTitle" : "序号",
			"bSortable": false,
			"sDefaultContent" : "",
			"sClass" : "center"
		},{
			"mDataProp" : "clientId",
			"sTitle" : "客户id",
			"bSortable": false,
			"sDefaultContent" : "",
			"bVisible":false,
			"sClass" : "center"
		}, {
			"mDataProp" : "loanCode",
			"sTitle" : "贷款申请号",
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
				return '<a href="javascript:void(0);" onclick="loan_query('+row.id+','+row.clientId+');" class="tablelink" >'+data+'</a>';
		     }
		}, {
			"mDataProp" : "loanBorrower",
			"sTitle" : "贷款人",
			"sDefaultContent" : "",
			"sClass" : "center",
			"sWidth":"10%"
		}, {
			"mDataProp" : "clientCardId",
			"sTitle" : "身份证号",
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "loanApplyDate",
			"sTitle" : "申请日期",
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
				var value = '';
				if(_is_empty(data)){
					value = '';
				}else{
					value = new Date(data).format('yyyy-MM-dd');
				}
				
	            return value;
		     }
		}, {
			"mDataProp" : "loanLimitApply",
			"sTitle" : "申请额度（元）",
			"sDefaultContent" : "",
			"sClass" : "center"
		}, {
			"mDataProp" : "finalLimit",
			"sTitle" : "终审额度（元）",
			"sDefaultContent" : "",
			"sClass" : "center"
			
		},  {
			"mDataProp" : "finalDeadline",
			"sTitle" : "终审期限（月）",
			"sDefaultContent" : "",
			"sClass" : "center"
			
		},{
			"mDataProp" : "loanAuditorName",
			"sTitle" : "审核人员",
			"sDefaultContent" : "",
			"sClass" : "center"
		},{
			"mDataProp" : "loanStatus",
			"sTitle" : "贷款状态",
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
				var returnStr = row.returnStatus==1?"(退回)":"(正常)";
		        return parent._local_loan_status[data]+returnStr||'异常';
		     }
		},{
			"mDataProp" : "loanStatus",
			"sTitle" : "审批状态",
			"bSortable": false,
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
				if(data>4){
					return '已审批';
				}else if(data==4){
					return '未审批';
				}
		        return'异常';
		     }
		},
		  {
			"mDataProp" : "en",
			"sTitle" : "操作",
			"bSortable": false,
			"sDefaultContent" : "",
			"sClass" : "center",
			"mRender": function (data, display, row) {
		      var id = row.id,clientId=row.clientId,status=row.loanStatus,loanApprover=row.loanApprover,loanProduct=row.loanProduct,loanLimitApply=row.loanLimitApply;
		      var parseStr = '<a href="jsp/loan/approve_loan_detail.jsp?id='+id+'&clientId='+clientId+'" class="tablelink" >查看</a>&nbsp;';
		      parseStr += '<a href="javascript:void(0);" onclick="loan_process('+id+');" class="tablelink">进度</a>&nbsp;';
		      if(status===4){
		    	  //待审批订单
		    	  audit.id = id;audit.clientId = clientId;audit.loanAuditor=row.loanAuditor;
		    	  
		    	  if(_is_empty(loanApprover)){
		    		  if(_is_not_empty(loginUser.sysApprover) &&_is_not_empty(loginUser.sysApprover.loanProductList) && loginUser.sysApprover.loanProductList.split(',').contains(loanProduct)){
		    			  var lonMinLimit  = loginUser.sysApprover.approverMinLimit||-1,lonMaxLimit = loginUser.sysApprover.approverMaxLimit||-1;
		    			  if(lonMinLimit == -1 && lonMaxLimit == -1){
		    				  parseStr += '<a href="javascript:AcceptOrder('+id+');" class="tablelink">受理审批</a>&nbsp;';
		    			  }else{
		    				  if(lonMinLimit == -1){
		    					  if(loanLimitApply<=lonMaxLimit){
		    						  parseStr += '<a href="javascript:AcceptOrder('+id+');" class="tablelink">受理审批</a>&nbsp;';
		    					  }
		    				  }else if(lonMaxLimit == -1){
		    					  if(loanLimitApply>=lonMinLimit){
		    						  parseStr += '<a href="javascript:AcceptOrder('+id+');" class="tablelink">受理审批</a>&nbsp;';
		    					  }
		    				  }else{
		    					  if(loanLimitApply<=lonMaxLimit && loanLimitApply>=lonMinLimit){
		    						  parseStr += '<a href="javascript:AcceptOrder('+id+');" class="tablelink">受理审批</a>&nbsp;';
		    					  }
		    				  }
		    			  }
		    		  }
		    		  
		    	  }else if(loanApprover==loginUser.id){
		    		  parseStr += '<a href="javascript:writeReport('+id+','+clientId+');" class="tablelink">填写审批</a>&nbsp;';
		    		  parseStr += '<a href="javascript:stopAudit('+id+');" class="tablelink">中止</a>&nbsp;';
		    	  }
		      }
		      return parseStr;
		    }
			
		}
		
		],
		"oLanguage": {
            "sUrl":"static_resources/language/lang-cn.txt" //这个是国际化，也就是汉化的各种文字数据源，写对url就行了
        }
        
	});

};

//初始化其他参数
var initOther = function(){
	//查询事件
	$('input[name="query_btn"]').click(function(){
		$('#approveTable').dataTable().fnDraw();
	});
	
	$('#loanStatus').mSelect({
		width:100,
		baseCode:'Loan_Status_Code'
	});
};
	
//自定义数据获取函数
var retrieveData = function( sSource, aoData, fnCallback ) {
		var array = $("#_form_search_default").serializeArray();
		array.push({name:"beanProxy[loanStatus_GreaterThanOrEqualTo]",value:4});
		array.push({name:"beanProxy[loanStatusStop]",value:0});
		array.push({name:'filterColumn',value:'loan_approver,or loan_approver is null '});
		aoData = parent._set_query_conditions(aoData,array);
	        $.ajax( {
	                type: "POST", 
	                url: sSource, 
	                cache : false,
	                dataType : "json",
	                data : aoData, 
	                success: function(resp) {
	                	if(resp && resp.state == 200){
	                		fnCallback(resp.datagrid);
	                		return false;
	                	}
	                	fnCallback(null);
	            }
	        });
};

//受理审批
var AcceptOrder = function(id){
	$.dialog.confirm('你确定要受理这条审批单吗？', function(){
		$.ajax({
	       	url:'sys/LoanExt/update',
	    	data:{loanApprover:loginUser.id,id:id},
	    	type:'post',
	    	dataType:'json',
	    	success:function(result){
	    	        if(result.state == "200"){
	    	        	$.dialog({
	    	 				icon: 'success.gif',
	    	 				title: '提示',
	    	 			    content: '受理申请单成功！',
	    	 			    ok: function(){
	    	 			    	$('#approveTable').dataTable().fnDraw();
	    	 			    }
	    	 			});
	    	        }else{
	    	        	$.dialog.alert('受理申请单失败！');
	    	        }
	    		}
	        });
	});
};

//填写报告
var writeReport = function(id,clientId){
	if(typeof(id)!='undefined' && typeof(clientId)!='undefined'){
		parent._do_goto_right(top.basePath+'jsp/loan/approve_loan_add.jsp?id='+id+"&clientId="+clientId);
	}
};

//中止订单
var stopAudit = function (id){
	$.dialog.confirm('你确定要中止这条审批单吗？', function(){
		$.ajax({
	       	url:'sys/LoanExt/stop',
	    	data:{pks:id},
	    	type:'post',
	    	dataType:'json',
	    	success:function(result){
	    	        if(result.state == "200"){
	    	        	$.dialog({
	    	 				icon: 'success.gif',
	    	 				title: '提示',
	    	 			    content: '中止申请单成功！',
	    	 			    ok: function(){
	    	 			    	$('#approveTable').dataTable().fnDraw();
	    	 			    }
	    	 			});
	    	        }else{
	    	        	$.dialog.alert('中止申请单失败！');
	    	        }
	    		}
	        });
	}, function(){
	});
};

//初始化
$(function(){
	Array.prototype.contains = function(obj) { 
		var i = this.length; 
		while (i--) { 
			if (this[i] === obj) { 
				return true; 
			} 
		} 
		return false; 
	};
	initGrid();
	initOther();
});
